{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Using a Maclaurin Series to Estimate $e$\n",
    "\n",
    "A [Maclaurin series](https://mathworld.wolfram.com/MaclaurinSeries.html) is an infinite series of terms that can be used to approximate more complex functions quickly.\n",
    "\n",
    "You're going to approximate $e^x$ by using the first few terms of the series.  The series equation for $e^x$ is this:\n",
    "\n",
    "$$\\sum_{n=0}^{\\infty} \\frac{x^n}{n!} = 1 + x + \\frac{x^2}{2} + \\frac{x^3}{6} \\ldots$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import e, factorial\n",
    "\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "fac = np.vectorize(factorial)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def e_x(x, terms=10):\n",
    "    \"\"\"Approximates $e^x$ using a given number of terms of the Maclaurin series\"\"\"\n",
    "    n = np.arange(terms)\n",
    "    return np.sum((x**n) / fac(n))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "20.085536923187664"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Actual:\n",
    "e**3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "N (terms)\tMaclaurin\tError\n",
      "1\t\t1.000\t\t19.086\n",
      "2\t\t4.000\t\t16.086\n",
      "3\t\t8.500\t\t11.586\n",
      "4\t\t13.000\t\t7.086\n",
      "5\t\t16.375\t\t3.711\n",
      "6\t\t18.400\t\t1.686\n",
      "7\t\t19.412\t\t0.673\n",
      "8\t\t19.846\t\t0.239\n",
      "9\t\t20.009\t\t0.076\n",
      "10\t\t20.063\t\t0.022\n",
      "11\t\t20.080\t\t0.006\n",
      "12\t\t20.084\t\t0.001\n",
      "13\t\t20.085\t\t0.000\n"
     ]
    }
   ],
   "source": [
    "print(\"N (terms)\\tMaclaurin\\tError\")\n",
    "\n",
    "for n in range(1, 14):\n",
    "    maclaurin = e_x(3, terms=n)\n",
    "    print(f\"{n}\\t\\t{maclaurin:.03f}\\t\\t{e**3 - maclaurin:.03f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}